<template>
    <div class="pageWrapper">
        <SearchBar class="form" @onSearch="handleSearch" @childFn="resetForm">
            <SearchBarItem label="支付订单号：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.paymentId"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="渠道支付订单号：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.flowId"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <!-- <SearchBarItem label="商户编码：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.merchantCode"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem> -->
            <SearchBarItem label="交易类型：" :labelLg="8">
                <Select
                    v-model="dataModule.transactionType"
                    placeholder="请选择"
                    :clearable="isClear"
                >
                    <Option
                        :value="item.key"
                        v-for="(item, key) in selectTransactionType"
                        :key="key"
                        >{{ item.value }}</Option
                    >
                </Select>
            </SearchBarItem>
            <SearchBarItem label="交易金额：" :labelLg="8">
                <Input
                    type="number"
                    v-model.trim="dataModule.payAmount"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="优惠金额：" :labelLg="8">
                <Input
                    type="number"
                    v-model.trim="dataModule.discount"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="银行流水号：" :labelLg="8">
                <Input
                    v-model.trim="dataModule.bankOrderId"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="通道费：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.serviceCharge"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="对账日期：" :labelLg="8">
                <DatePicker
                    type="daterange"
                    ref="createDatePicker"
                    split-panels
                    transfer
                    placeholder="请选择"
                    @on-change="createTime"
                    :value="reconciliationValue"
                ></DatePicker>
            </SearchBarItem>
            <SearchBarItem label="支付时间：" :labelLg="8">
                <DatePicker
                    type="daterange"
                    ref="payDatePicker"
                    split-panels
                    transfer
                    placeholder="请选择"
                    @on-change="payTime"
                ></DatePicker>
            </SearchBarItem>
        </SearchBar>
        <RemoteTable
            :namespace="namespace"
            :columns="columns11"
            :selected="batchData"
            :showPageInfo="false"
            :isFixedHeader="true"
            :showCount="true"
            @onSortChange="onSortChange"
            @onSelectionChange="getListChecked"
        >
          <template #extra>
            <Authc permissions="trade:settlement:cmb">
              <Button @click="goToBatch">批量处理</Button>
            </Authc>
            <Authc permissions="trade:settlement:cmb">
              <Button @click="goToBank">比对银行流水</Button>
            </Authc>
          </template>

        </RemoteTable>
        <br />
        <Row>
            <Col span="12" offset="11">
                <Button type="primary" @click="loadMore" :disabled="isDisabledloadBtn">加载更多</Button>
            </Col>
        </Row>
        <Modal
            v-model="modalBank"
            width="700"
            :mask-closable="false"
            title="比对银行流水">
           <Form :label-width="100">
                <FormItem label="交易日期:">
                    <DatePicker type="date" @on-change="changeDate" format="yyyy-MM-dd" v-model="modelDate" placeholder="选择单日日期"></DatePicker>
                </FormItem>
                <FormItem>
                    <div class="remack_one">
                        <div>查询结果:</div>
                        <div v-if=" isShwo && isShowRemack">交易中台有{{ modelData.systemCount }}条流水记录，服务器有{{ modelData.serverCount }}条流水记录，差异{{ modelData.errorCount }}条流水记录对应交易中台内{{ modelData.subOrderCount }}条子订单；</div>
                        <div v-if=" isShwo && isShowSub">是否对子订单标注异常原因？（原因为：平台有-招行滞后提供对账单）</div>
                        <div v-if=" isShwo && isShowSubDate">此日期已被标注。</div>
                    </div>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="primary" :disabled="isDisabledDateBtn" :loading="modalLoading" @click="ok">比对查询</Button>
                <Button type="primary" :disabled="isDisabledOneBtn" @click="handleOne">标注原因</Button>
                <Button type="primary" @click="cancel"> 返 回 </Button>
            </div>

        </Modal>

        <Modal
            v-model="modalOk"
            title="提示"
            width="300"
            :mask-closable="false"
            @on-ok="showOk"
            @on-cancel="showCancel">
            <p>提交后不可更改差异原因，是否确认提交？</p>
        </Modal>
    </div>
</template>
<script>
import {
    Button,
    Input,
    Modal,
    Message,
    DatePicker,
    Select,
    Option,
    Row,
    Col,
    Form,
    FormItem
} from "view-design";
import RemoteTable from "@/components/RemoteTable";
import SearchBar from "@/components/SearchBar";
import RemoteSelect from "@/components/RemoteSelect";
import { namespace } from "../Module/settlementAbnormalModule";
import Authc from "@/components/Authc";
import Tables from "@/components/tables";
import Action from "./Action";
import config from "@/utils/config";
import appService from "@/utils/appService";
import util from "@/utils/util";

export default {
    name: "settlementAbnormal",
    components: {
        RemoteTable,
        SearchBar,
        SearchBarItem: SearchBar.SearchBarItem,
        RemoteSelect,
        Authc,
        Action,
        Tables,
        Button,
        Input,
        Modal,
        Message,
        DatePicker,
        Select,
        Option,
        Row,
        Col,
        Form,
        FormItem
    },
    data() {
        return {
            isShwo: false,
            isShowSub: true,
            isShowSubDate: false,
            modelData: {},
            modalOk: false,
            isShowRemack: false,
            isDisabledOneBtn: true,
            isDisabledDateBtn: true,
            modelDate: '',
            modalLoading: false,
            modalBank: false,
            requireUrl: "",
            namespace: namespace,
            isClear: true,
            loading: true,
            modal1: false,
            dataModule: {}, /** 查询条件 **/
            batchData: [], /** 存放批量处理的数据 **/
            currentPage: 1, /** 用来控制加载更新 **/
            isDisabledloadBtn: false, /** 控制加载更多按钮 **/
            selectTransactionType: [], /** 交易类型 **/
            reconciliationValue: [], /** 存放跳转过来的日期，用来显示的 **/
            tableData: [],
            columns11: [
                {
                    title: "平台流水",
                    align: "center",
                    children: [
                        // {
                        //     type: "selection",
                        //     align: "center",
                        //     minWidth: 55
                        // },
                        {
                            title: "序号",
                            type: "index",
                            align: "center",
                            minWidth: 80
                        },
                        {
                            title: "交易类型",
                            key: "transactionTypeCn",
                            align: "center",
                            minWidth: 100
                        },
                        {
                            title: "支付订单号",
                            key: "paymentId",
                            align: "center",
                            minWidth: 100
                        },
                        {
                            title: "渠道支付订单号",
                            key: "flowId",
                            align: "center",
                            minWidth: 205
                        },
                        // {
                        //     title: "商户编码",
                        //     key: "merchantCode",
                        //     align: "center",
                        //     minWidth: 100
                        // },
                        {
                            title: "订单金额(元)",
                            key: "orderAmount",
                            align: "center",
                            minWidth: 110,
                            render: function(h, data) {
                                let item = data.row.orderAmount / 100;
                                return h("span", util.toMoney(item));
                            }
                        },
                        {
                            title: "优惠金额(元)",
                            key: "discount",
                            align: "center",
                            minWidth: 110,
                            render: function(h, data) {
                                let item = data.row.discount / 100;
                                return h("span", util.toMoney(item));
                            }
                        },
                        {
                            title: "交易金额(元)",
                            key: "payAmount",
                            align: "center",
                            minWidth: 110,
                            render: function(h, data) {
                                let item = Math.abs(data.row.payAmount / 100);
                                return h("span", util.toMoney(item));
                            }
                        },
                        {
                            title: "通道费(元)",
                            key: "serviceCharge",
                            align: "center",
                            minWidth: 100,
                            render: function(h, data) {
                                let item = data.row.serviceCharge / 100;
                                return h("span", util.toMoney(item));
                            }
                        }
                    ]
                },
                {
                    title: "银行流水",
                    align: "center",
                    children: [
                        {
                            title: "订单金额(元)",
                            key: "bankOrderAmount",
                            align: "center",
                            minWidth: 110,
                            render: function(h, data) {
                                let item = data.row.bankOrderAmount / 100;
                                return h(
                                    "span",
                                    util.toMoney(item)
                                );
                            }
                        },
                        {
                            title: "优惠金额(元)",
                            key: "bankDiscount",
                            align: "center",
                            minWidth: 110,
                            render: function(h, data) {
                                let item = data.row.bankDiscount / 100;
                                return h("span", util.toMoney(item));
                            }
                        },
                        {
                            title: "交易金额(元)",
                            key: "bankPayAmount",
                            align: "center",
                            minWidth: 110,
                            render: function(h, data) {
                                let item = Math.abs(data.row.bankPayAmount / 100);
                                return h(
                                    "span",
                                    util.toMoney(item)
                                );
                            }
                        },
                        {
                            title: "通道费(元)",
                            key: "bankServiceCharge",
                            align: "center",
                            minWidth: 110,
                            render: function(h, data) {
                                let item = data.row.bankServiceCharge / 100;
                                return h(
                                    "span",
                                    util.toMoney(item)
                                );
                            }
                        },
                        {
                            title: "交易时间",
                            key: "payTime",
                            align: "center",
                            minWidth: 150
                        }
                    ]
                },
                {
                    title: "对账结果",
                    align: "center",
                    // fixed: "right",
                    children: [
                        {
                            title: "对账时间",
                            key: "reconciliationTime",
                            align: "center",
                            // fixed: "right",
                            minWidth: 150
                        },
                        {
                            title: "差异(元)",
                            key: "diffAmount",
                            align: "center",
                            // fixed: "right",
                            minWidth: 100,
                            render: (h, params) => {
                                let item = params.row.diffAmount / 100;
                                return h("span", util.toMoney(item));
                            }
                        },
                        {
                            title: "操作",
                            key: "action",
                            minWidth: 100,
                            align: "center",
                            // fixed: "right",
                            permissions: ["trade:settlement:cmb"],
                            render: function(h, data) {
                                return h(Action, {
                                    props: {
                                        row: data.row
                                    }
                                });
                            }
                        }
                    ]
                }
            ]
        };
    },
    created() {

        /**
         * 如果 url 没有带参数，就重置请求参数
         * 有就添加到 vuex
         * **/
        let timeBegin = util.getUrlParam('reconciliationDateBegin');
        let timeEnd = util.getUrlParam('reconciliationDateBegin');
        let status = util.getUrlParam('reconciliationStatus');
        if( timeBegin ) {
            this.$store.commit(`${namespace}/setQuery`, {
                reconciliationDateBegin: timeBegin,
                reconciliationDateEnd: timeEnd,
                reconciliationStatus: status
            });
            this.$set(this.reconciliationValue, 0, timeBegin);
            this.$set(this.reconciliationValue, 1, timeEnd);
        } else {
            this.$store.commit(`${namespace}/reviseQuery`);
        }
        this.getKey();
    },
    methods: {
        /**
         *      二次确认框
         */
        async showOk () {
            try {
                let data = {
                    date: this.modelDate,
                    remark: '平台有-招行滞后提供对账单'
                }
                let res = await this.$store.dispatch(`${namespace}/save`, data);

                if (res.ret === 0) {
                    this.modalBank = false;
                    this.modalOk = false;
                    this.isShowSub = true;
                    this.isShowSubDate = false;
                } else {
                    this.isShowSub = false;
                    this.isShowSubDate = true;
                    this.$Message.error({
                        content: res.msg
                    });
                }
            } catch (error) {

            }
            this.modalOk = false;
        },

        showCancel () {
            this.modalOk = false;
        },

        /**
         *      弹窗
         */
        goToBank () {
            this.modalBank = true;
            this.modelDate = '';
            this.modelRemark = '';
            // this.isShowRemack = true;
        },
        handleOne () {
            this.modalOk = true;

        },
        changeDate (date) {
            this.modelDate = date;
            if (date) {

                this.isDisabledDateBtn = false;
            } else {
                this.isDisabledDateBtn = true;
            }
            console.log(date)
        },
        async ok () {
            try {
                let params = {
                    date:  this.modelDate
                }
                this.modalLoading = true;
                let res = await this.$store.dispatch(`${namespace}/comparison`, params);
                if (res.data.ret === 0) {
                    this.modalLoading = false;
                    this.modelData = res.data.data;
                    this.isShwo = true;
                    this.isShowRemack = true;

                    // this.modelData = {
                    //     subOrderCount: 0,
                    //     comparisonStatus: 'wait',
                    //     serverCount: 114,
                    //     errorCount: 123,
                    //     systemCount: 23456
                    // }

                    if (this.modelData.subOrderCount > 0) {
                        this.isDisabledOneBtn = false;
                    } else {
                        this.isShowSub = false;
                        this.isShowSubDate = false;
                        this.isDisabledOneBtn = true;
                    }
                    if (this.modelData.comparisonStatus === 'success') { // comparisonStatus; wait 未被标注  success  已标注
                        this.isShowSub = false;
                        this.isShowSubDate = true;
                        this.isDisabledOneBtn = true;
                    } else {
                        this.isShowSub = true;
                        this.isShowSubDate = false;
                    }
                }
            } catch (error) {
                this.$Message.error({
                    content: error
                });
            }
        },
        cancel () {
            this.modalBank = false;
        },

        /** 获取搜索条件字典 **/
        async getKey() {
            try {
                let res = await this.$store.dispatch(`${namespace}/getMerchantSearchKey`);
                let data = res.data.data;
                this.selectTransactionType = data.transactionType;
            } catch (error) {
                this.$Message.error({
                    content: error
                });
            }
        },
        /** 搜索 **/
        async handleSearch() {
            this.currentPage = 1;
            let obj = {
                currentPage: 1,
                pageSize: 50,
                payAmount: this.dataModule.payAmount * 100,
                discount: this.dataModule.discount * 100
            };
            await this.$store.dispatch(`${namespace}/query`, { ...this.dataModule,...obj });
        },
        onSortChange(sort) {
            if (sort.order === "normal") {
                this.queryParam.order = [];
            } else {
                this.queryParam.order = [sort.key + " " + sort.order];
            }
            this.handleSearch();
        },
        /** 清空所有查询条件 **/
        resetForm() {
            this.$set(this.dataModule, "paymentId", "");
            this.$set(this.dataModule, "flowId", "");
            this.$set(this.dataModule, "merchantCode", "");
            this.$set(this.dataModule, "transactionType", "");
            this.$set(this.dataModule, "payAmount", "");
            this.$set(this.dataModule, "discount", "");
            this.$set(this.dataModule, "serviceCharge", "");
            this.$set(this.dataModule, "bankOrderId", "");
            // 清空时间选择
            this.$refs["createDatePicker"].handleClear();
            this.$refs["payDatePicker"].handleClear();
        },
        /** 对账日期 **/
        createTime(date, type) {
            this.dataModule.reconciliationDateBegin = date ? date[0] : "";
            this.dataModule.reconciliationDateEnd = date ? date[1] : "";
        },
        /** 支付时间 **/
        payTime(date, type) {
            this.dataModule.payTimeBegin = date ? date[0] : "";
            this.dataModule.payTimeEnd = date ? date[1] : "";
        },
        /** 加载更多 **/
        async loadMore() {
            try {
                let timeBegin = util.getUrlParam('reconciliationDateBegin');
                let timeEnd = util.getUrlParam('reconciliationDateBegin');
                let status = util.getUrlParam('reconciliationStatus');
                let param
                if( timeBegin ) {
                    param = {
                        reconciliationDateBegin: timeBegin,
                        reconciliationDateEnd: timeEnd
                    }
                }

                this.isDisabledloadBtn = true; /** 每次请求都禁止按钮点击 **/
                let obj = {
                    currentPage: ++this.currentPage,
                    pageSize: 50,
                    reconciliationStatus: "un_success"
                };
                /** 因为不是翻页，所以重新写了一个列表的请求 **/
                let res = await this.$store.dispatch(`${namespace}/getMoreList`, { ...param, ...this.dataModule, ...obj });
                let listData = res.data.data.list;
                if (listData.length != 0) {
                    /** 拿到数据，就拼接到 vuex 里面 **/
                    this.$store.commit(`${namespace}/pushDataToList`, listData);
                } else {
                    --this.currentPage;
                    this.$Message.info({
                        content: '没有更多数据了！'
                    });
                }
                this.isDisabledloadBtn = false;
            } catch (error) {
                this.$Message.error({
                    content: error
                });
            }
        },
        /** 列表选择 **/
        getListChecked(data) {
            this.batchData = data;
        },
        goToBatch() {
            // if (this.batchData.length == 0) {
            //     this.$Message.warning({
            //         content: "请选择需要处理的内容"
            //     });
            //     return;
            // }
            /** 把批量数据存起来放到 vuex 里面 **/
            // this.$store.commit(`${namespace}/saveState`, {
            //   batchData: this.batchData
            // });
            /** 把批量数据存起来放到 本地，可以刷新 **/
            // sessionStorage.setItem(
            //     `${namespace}/batchData`,
            //     JSON.stringify(this.batchData)
            // );
            this.$router.push({
                path: "/settlement/admin/SettlementCenter/SettlementAbnormalBatchProcessing"
            });
        }
    },
};
</script>
<style scoped>
.remack_one {
    border: 1px solid #ddd;
    border-radius: 4px;
    width: 100%;
    height: 178px;
    padding: 8px;
}
</style>
